/**
 * @author HuangWenJing
 * 
 */
(function() {
	$.geneChart = {
		basePath : jsContextPath ? jsContextPath + '/' : '',
		render : {// 设置形状
			Column : 'COLUMN',
			Area : 'AREA',
			Line : 'LINE'
		},
		yaxis : {// 设置主、次y轴
			Primary : 'P',
			Second : 'S'
		},
		exportAction : {// 导出类型，save:将图片保存到服务器上
			download : 'download',
			save : 'save'
		},
		exportFormat : {// 导出格式
			jpg : 'JPG',
			png : 'PNG',
			pdf : 'PDF'
		},
		exportBtnMsg : {
			download : '下载',
			save : '保存'
		},
		constant : {
			render : 'renderas',
			yaxis : 'parentyaxis'
		},
		getScript : function(src) {// 动态加载js文件
			$(document)
					.append(
							"<script type='text/javascript' src='" + src
									+ "'</script>");
		},
		unload : function() {
			var items = FusionCharts.items;
			for ( var item in items) {
				FusionCharts(item).dispose();
			}
		},
		exception : {
			render : 'renderas:请选择Column、Area、Line之一',
			yaxis : 'parentyaxis:请选择Primary、Second之一'
		},
		validate : function(el, obj) {
			for ( var i in obj) {
				var msg = el.id + ':';
				var o = obj[i];
				msg += this.isNotNull(o.code) ? o.code + '----' : '';
				if (this.isEception(o, 'render', msg))
					return false;
				if (this.isEception(o, 'yaxis', msg))
					return false;
			}
			return true;
		},
		isEception : function(measure, type, msg) {
			var statu = false;
			var o = this;
			var item = measure[this.constant[type]];
			if ($.type(item) != 'undefined') {
				var constant = o[type];
				if ($.type(constant[item]) == 'undefined') {
					var message = this.isNotNull(msg) ? msg : '';
					alert(message + $.geneChart.exception[type]);
					statu = true;
				} else {
					measure[this.constant[type]] = constant[item];
				}
			}
			return statu;
		},
		isNotNull : function(value) {
			return (value && $.type(value) != 'undefined') ? true : false;
		},
		getSwfUrl : function(chartConfig) {
			var msg = chartConfig.nodataMsg;
			var type = chartConfig.chartType;
			// msg = this.isNotNull(msg) ? '?ChartNoDataText=' + msg +
			// '&_url=fusioncharts.com' : '';
			var swfUrl = window[type];
			if (swfUrl) {
				swfUrl = this.isNotNull(msg) ? this.appendParam(swfUrl,
						'ChartNoDataText', msg) : '';
				swfUrl = this.appendParam(swfUrl, '_url', 'fusioncharts.com');

				// 用绝对路径获取swf，避免jsp页面没有设置basePath导致图形空白的情况
				chartConfig.swfUrl = $.geneChart.basePath + swfUrl;
			}

		},
		appendParam : function(url, pName, value) {
			var mark = '?';

			if (url.indexOf(mark) > -1) {
				mark = '&';
			}
			if (url) {
				url += mark + pName + '=' + value;
			}

			return url;
		},
		getTimeStamp : function() {
			return ("" + (new Date()).valueOf());
		},
		getTypeName : function(el) {
			var name = el.id || el.className || el.name || 'chart';
			return name;
		},
		getQueryString : function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return unescape(r[2]);
			}
			return null;
		},
		getParamsData : function(data) {
			data = obj2str(data);
			return data;
		},
		getMeasure : function(measure) {
			var newMeasure = [];
			for ( var i in measure) {
				var mea = measure[i];
				var m = this.measureHandler(mea);
				newMeasure.push(m);
			}
			return newMeasure;
		},
		measureHandler : function(mea) {
			var m = {};
			for ( var key in mea) {
				var value = mea[key];
				if ('link' == key) {
					m.hasLink = !!mea[key];
				} else {
					m[key] = value;
				}
			}
			return m;
		},
		arrayContains : function(array, objectToFind) {
			for ( var i in array) {
				if (objectToFind == array[i]) {
					return true;
				}
			}
			return false;
		},
		getExport : function(el, config) {
			var exporter = config.exporter || {};
			if (!!exporter.showExportDiv) {
				// 清理下载元素缓存信息
				$("." + this.getTypeName(el) + "_showDiv").remove();

				var div = $(
						'<div id="' + this.getTypeName(el) + '_showDiv_'
								+ this.getTimeStamp() + '" class="fcExport '
								+ this.getTypeName(el) + '_showDiv"></div>')
						.insertAfter(el);
				var exportAction = this.exportAction[exporter.exportAction] || 'download';
				var fun = $.isFunction(exporter.exportFun) ? exporter.exportFun
						: function() {
							alert('请配置导出的函数');
						};

				var aId = "a" + this.getTypeName(el) + '_showHref_'
						+ this.getTimeStamp();
				var a = $(
						'<a id="'
								+ aId
								+ '" class="aGeneChartExport" href="javascript:void(0);">'
								+ this.exportBtnMsg[exportAction] + '</a>')
						.appendTo(div);
				a.click(function() {
					fun.call($(el));
				});
				config.displayExpDiv = div;
			}
			exporter.exportFormat = this.exportFormat[exporter.exportFormat] || 'JPG';
			exporter.exportFileName = encodeURI(encodeURI(exporter.exportFileName));// 转两次码，IE下中文可以显示，firefox下中文有问题
			delete exporter.showExportDiv;
			delete exporter.exportFun;
			config.chartStyle = $.extend(true, config.chartStyle, exporter);

		},
		exportFun : function() {
			this.exportChart();
		},
		updateCharts : function() {
			var charts = $(":FusionCharts");
			charts.each(function() {
				var chart = this;
				var parent = $(chart).parent();
				parent.updateChart();
			});
		},
		fusionChart : {
			drillDown : function(param) {
				var obj = $.parseJSON(param);
				var id = obj.chartId;
				var data = obj.data;
				var code = obj.meaCode;

				var parent = $('#' + id).parent()[0], link, dimData = code;
				if (parent.defaultConfig_.dynamicMeasureBean) {
					link = parent.defaultConfig_.link;
					if (parent.defaultConfig_.dimDataMap) {
						dimData = parent.defaultConfig_.dimDataMap[code];
					}
					var aliasMap;
					if (aliasMap = parent.defaultConfig_.aliasMap) {
						for ( var key in data) {
							var alias = aliasMap[key];
							if (alias) {
								data[alias] = data[key];
								delete data[key];
							}
						}
					}
				} else {
					link = this.getLink(parent.defaultConfig_, code);
				}
				if ($.isFunction(link)) {
					link.call(parent, data, dimData);
				} else if ($.type(link) == 'string' && '' != link) {
					window.open(link);
				}
			},
			getLink : function(config, code) {
				var measure = config.measure;
				for ( var i in measure) {
					var m = measure[i];
					if (code == m.code) {
						return m.link;
					}
				}
				return null;
			},
			loadComplete : function(config, evt, args) {
				if ($.isFunction(config.loadComplete)) {
					config.loadComplete.call(window, evt, args);
				}
			},
			getChart : function(obj, config, chartConfig) {
				var postData = $.extend(true,
						config.formId ? getPostData(config.formId) : {},
						config.params);
				postData && (postData.reportType = config.reportType);
				postData.dimension = config.dimension;
				postData.measure = $.geneChart.getMeasure(config.measure);
				postData.chartStyle = config.chartStyle;
				postData.isSingle = !!config.isSingle;
				postData.chartId = chartConfig.id;
				postData.dynamicMeasureBean = config.dynamicMeasureBean;
				postData.hasLink = !!config.link;
				var forwardTotal = config.forwardTotal, backTotal = config.backTotal;
				postData.forwardTotal = forwardTotal;
				postData.backTotal = backTotal;

				var parent = $(obj).parent();
				var displayExpDiv = config.displayExpDiv || null;

				$.utils.noData.hideNoDataInfo(obj);

				var icon = config.icon;

				parent.find('#' + chartConfig.id).remove();

				$.utils.loading.show(obj);

				$
						.ajax( {
							url : config.url,
							type : "post",
							data : $.geneChart.getParamsData(postData),
							dataType : "json",
							complete : function() {
							},
							success : function(data) {
								$.utils.loading.hide(obj);

								var beforeHandler = config.beforeHandler;
								if ($.isFunction(beforeHandler)) {
									beforeHandler.call(obj, data, config,
											chartConfig);
								}

								var result = $.geneChart.isNotNull(data.chart) ? data.chart
										: {};

								config.dimDataMap = data.dimDataMap;
								config.aliasMap = data.aliasMap;

								chartConfig.dataSource = result;
								chartConfig.infoMap = data.infoMap;
								var chart = FusionCharts(chartConfig.id);
								if (chart) {
									FusionCharts(chartConfig.id).dispose();
								}
								obj.insertFusionCharts(chartConfig);

								obj.bind("fusionchartsnodatatodisplay",
										function(e, args) {
											$.utils.noData.showNoDataInfo(obj,
													config.nodata);
											$(obj).hideExpDiv();
										});

								// fusion chart的事件绑定，dom必须有id
								obj
										.bind(
												"fusionchartsloaded",
												function(e, args) {
													$(obj).displayExpDiv();
													args.chartConfig = chartConfig;
													$.geneChart.fusionChart
															.loadComplete(
																	config, e,
																	args);

													var afterHandler = config.afterHandler;
													if ($
															.isFunction(afterHandler)) {
														afterHandler.call(obj,
																data, config,
																chartConfig);
													}
												});

							}
						});
			}
		}
	};

	$(window).bind('unload', $.geneChart.unload);

	$.fn.geneChart = function(config, chartConfig) {
		this
				.each(function() {
					var el = this;
					var defaultConfig_ = {
						url : $.geneChart.basePath + 'fusionChart/generate.do',
						formId : 'queryForm',
						handler : $.geneChart.fusionChart.getChart,
						beforeHandler : null,// 前处理
						afterHandler : null,// 后处理
						params : {},
						dimension : [],// 维度，对应查询的sql列名
						measure : [],// 度量值，code:度量值对应查询sql的列名，seriesname:显示的中文名，renderas:对应的图形，parentyaxis:设置主、次y轴，link:下钻链接
						dynamicMeasureBean : null,
						link : null,
						nodata : {
							enable : true,
							icon : 'table',
							refresh : function() {
								$(this).updateChart();
							}
						},
						chartStyle : {
							basefont : "Arial",// 字体类型
							basefontsize : "12",// 字体号
							bgColor : 'ffffff',// 背景颜色
							useroundedges : '0',// 柱子是否为圆边
							legendBorderThickness : '0',// 图例边框粗细
							minimiseWrappingInLegend : '0',// 图例文字是否换行
							legendShadow : '0',// 图例是否有阴影
							showLegend : '1',// 是否显示图例
							legendPosition : 'BOTTOM',// 图例位置，默认在底部，RIGHT:图例在右边
							// palette : '2',// fusion chart自带的颜色方案，值范围：1-5
							paletteColors : '519EDE,FDE35B,95D36B,B0A6EF,EDA5F3,EAA66E,C6CE93,64DBBB,E8ADAD,B9BDC1,' + '75C7F1,FCCA81,F5978A,B9DF71,9FA1F2,9CBCE3,C8A8EF,F39AE5,92E5AE,C499EC',// 默认的颜色方案
							showvalues : '0',// 是否在图上显示数值
							showLabels : '1',
							formatNumberScale : '0',// 是否在y轴上加缩写（设置为1：自动加缩写，例如k,m）
							forcedecimals : '0',// 如果decimals设置为2，数值为整数时可取整
							thousandSeparator : ',',// 数值千分位分隔符
							decimals : '2',// 主y轴数据精度
							numberPrefix : '',// 主y轴数据前缀单位
							numberSuffix : '',// 主y轴数据后缀单位
							yAxisValueDecimals : '0', // 主y轴上的数值精度
							sFormatNumberScale : '0',// 是否在次y轴上加缩写
							sDecimals : '2',// 次y轴数据精度
							sNumberPrefix : '', // 次y轴数据前缀单位
							sNumberSuffix : '%',// 次y轴数据后缀单位
							sYAxisValueDecimals : '0',
							showBorder : '0',
							borderColor : 'CCCCCC',
							legendBgColor : 'FFFFFF',
							legendBorderColor : '666666',
							xaxisName : '',
							toolTipSepChar : ' ',// tooltips分隔符
							showSumAtEnd : '1',// 瀑布Chart是否默认加入汇总。1:是,0:否
							sumlabel : '合计',
							showconnectors : '0',// 瀑布Chart是否是否显示连接线
							connectorDashed : '0',// 连接线是否是虚线showconnectors:1是起效
							positivecolor : '',// 正数column颜色
							negativecolor : '',// 负数column颜色
							use3dlighting : '0',
							plotGradientColor : '',
							showPlotBorder : '1',
							plotBorderThickness : '2',
							plotBorderAlpha : '100',
							plotBorderColor : 'FFFFFF',
							legendBorderAlpha : '0',
							showAlternateHGridColor : '0',// 是否隔行换色
							showAlternateVGridColor : '0',
							divLineIsDashed : '1',
							plotSpacePercent : '50',
							// toolTipBgColor:'72777f',
							// toolTipBorderColor:'72777f',
							outCnvbaseFontColor : '838b96',
							canvasBorderAlpha : '10',
							// baseFontColor:'ffffff',
							divLineColor : 'b9b9b9',
							yaxisNameWidth : '20',
							rotateYAxisName : '0',
							pyAxisNameWidth : '20',
							syAxisNameWidth : '20',
							numDivLines : 5,
							seriesNameInToolTip : 0,
							showShadow : 0,
							connectNullData : 1,
							labelDisplay:'WRAP'
						},
						isSingle : false,// 是否单维度，对于没有多维的图形，这个标志必须设置为true，例如饼图、环图、瀑布图
						reportType : null,
						exporter : {
							showExportDiv : false,
							exportFun : $.geneChart.exportFun,
							exportEnabled : '1',
							exportHandler : 'servlet/FCExporter',
							exportAction : 'download',
							exportFormat : 'jpg',
							exportTargetWindow : '_self',
							exportFileName : '',
							exportDialogColor : 'e1f5ff',
							exportDialogBorderColor : '0372ab',
							exportDialogFontColor : '0372ab',
							exportDialogPBColor : '0372ab',
							exportDialogMessage : '正在生成图片...'
						},
						forwardTotal : {
							enable : false,
							label : '全部'
						},
						backTotal : {
							enable : false,
							label : '全部'
						}
					};
					var defChartConf_ = {
						chartType : 'MSColumn2D',// 图形类别
						id : $.geneChart.getTypeName(el) + '_'
								+ $.geneChart.getTimeStamp(),// 图形ID
						width : '100%',// 自适应宽度
						height : 500,// 高度
						detectFlashVersion : 0,// 检测flash版本
						autoInstallRedirect : 0,// 自动安装flash
						dataFormat : 'json',// 图形数据的格式（可为xml）
						nodataMsg : '无相关结果',// 无结果时显示的文本信息
						debugMode : '0'
					};
					defaultConfig_ = $.extend(true, defaultConfig_, config);
					$.geneChart.getExport(el, defaultConfig_);
					defaultConfig_.chartStyle.exportAtClient = '0';// 在服务器端导出
					if (!$.geneChart.validate(this, defaultConfig_.measure)) {
						return;
					}
					defChartConf_ = $.extend(true, defChartConf_, chartConfig);
					$.geneChart.getSwfUrl(defChartConf_);

					if (!$.isFunction(defaultConfig_.handler)) {
						alert('请配置handler函数');
					}
					this.defaultConfig_ = defaultConfig_;
					this.defChartConf_ = defChartConf_;

					if ($.isFunction(defaultConfig_.handler)) {
						defaultConfig_.handler($(this), defaultConfig_,
								defChartConf_);
					}

				});
	};

	$.fn.extend( {
		geneStackChart : function(config, chartConfig) {
			this.each(function() {
				var config_ = {
					url : $.geneChart.basePath + 'fusionChart/geneStack.do',// 堆叠图特殊处理
					dimension : [],
					stack : {},
					params : {}
				};
				var chartConfig_ = {
					chartType : 'MSStackedColumn2DLineDY'
				};

				config_ = $.extend(true, config_, config || {});
				chartConfig_ = $.extend(true, chartConfig_, chartConfig || {});

				var stack = config_.stack;
				var measure = [];
				for ( var i in stack.dataset) {
					var e = stack.dataset[i];
					measure.push(e);
				}
				measure.push(stack.lineset);

				config_.measure = measure;

				stack.dataset = $.geneChart.getMeasure(stack.dataset);
				stack.lineset = $.geneChart.measureHandler(stack.lineset);
				config_.params.stack = stack;
				$(this).geneChart(config_, chartConfig_);
			});
		},
		updateChart : function(config, chartConfig) {
			this.each(function() {
				config = config || {};
				chartConfig = chartConfig || {};
				this.defaultConfig_ = $.extend(true, this.defaultConfig_,
						config);
				this.defChartConf_ = $.extend(true, this.defChartConf_,
						chartConfig);
				$.geneChart.getSwfUrl(this.defChartConf_);

				if ($.isFunction(this.defaultConfig_.handler)) {
					this.defaultConfig_.handler($(this), this.defaultConfig_,
							this.defChartConf_);
				}
			});
		},
		updateFusionChart : function(chartConfig) {
			this
					.each(function() {
						var chartConfig_ = chartConfig || {};
						chartConfig_ = $.extend(true, this.defChartConf_,
								chartConfig_);
						var chart = FusionCharts(chartConfig_.id);
						if (chart) {
							FusionCharts(chartConfig.id).dispose();
						}
						$(this).insertFusionCharts(chartConfig);
						$(this).unbind("fusionchartsloaded");
						$(this).unbind("fusionchartsnodatatodisplay");
					});
		},
		exportChart : function(exportConf) {
			var charts = this.find(":FusionCharts");
			exportConf = exportConf || {};
			var format = $.geneChart.exportFormat[exportConf.exportFormat];
			charts.each(function() {
				var config = $(this).parent()[0].defaultConfig_ || {};
				exportConf.exportFormat = format
						|| config.chartStyle.exportFormat;
				var chartObject = getChartFromId(this.id);
				chartObject.exportChart(exportConf);
			});
		},
		displayExpDiv : function(isNotShow) {
			var config = this[0].defaultConfig_;
			var div = config.displayExpDiv;
			if (div) {
				!!isNotShow ? $(div).hide() : $(div).show();
			}
		},
		hideExpDiv : function() {
			this.displayExpDiv(true);
		}
	});

	function getPostData(formId, multOprtJoin) {
		var param = {};
		multOprtJoin && (param.multOprtJoin = multOprtJoin);
		var inputs = $('#' + formId + ' :input');
		inputs.each(function(i, obj) {
			var name = $(this).attr('name');
			var val = $(this).val();

			if (name && name.length > 0 && val != null) {
				if (typeof val != 'string') {// 多选下拉框等
					val = val.join(multOprtJoin);
				}
				param[name] = val;
			}
		});
		return param;
	}
	;

	function obj2str(obj) {
		return obj2uriArray(obj, '').join('&');
		function obj2uriArray(obj, prev) {
			var type = $.type(obj);
			var ret = [];
			if (type == 'object') {
				for ( var field in obj) {
					var value = obj[field];
					if (isSimpleValue(value)) {
						var quot = (prev && prev != '') ? '.' : '';
						ret.push(prev + quot + field + '=' + encodeURI(value));
					} else {
						var subRets = obj2uriArray(obj[field],
								(prev ? prev + '.' : '') + field);
						for ( var i = 0; i < subRets.length; i++) {
							ret.push(subRets[i]);
						}
					}
				}
			} else if (type == 'array') {
				for ( var i = 0; i < obj.length; i++) {
					var value = obj[i];
					if (isSimpleValue(value)) {
						ret.push(prev + '[' + i + ']=' + encodeURI(value));
					} else {
						var subRets = obj2uriArray(obj[i], prev + '[' + i + ']');
						for ( var j = 0; j < subRets.length; j++) {
							ret.push(subRets[j]);
						}
					}
				}
			}

			return ret;
		}
		function isSimpleValue(obj) {
			return $.type(obj) === "boolean" || $.type(obj) === "number"
					|| $.type(obj) === "string" || $.isFunction(obj);
		}
	}
	;

})();
